﻿using System.Collections.Generic;
using Tools;
using UnityEngine;
using UnityEngine.AddressableAssets;

namespace UI
{
    public class UIManager : SimpleSingletonProvider<UIManager>
    {
        /// <summary>
        /// UI根节点
        /// </summary>
        public Transform UIRoot;
        /// <summary>
        /// 缓存窗口
        /// </summary>
        private readonly Dictionary<string, WindowBase> _cachedWindowDict = new Dictionary<string, WindowBase>();

        //非持久化UI才能进入栈
        private readonly Stack<WindowBase> _windowStack = new Stack<WindowBase>();

        /// <summary>
        /// 当前界面
        /// </summary>
        public WindowBase CurrentWindow { get; private set; }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="uiRoot"></param>
        public void InitUI(Transform uiRoot)
        {
            UIRoot = uiRoot;
        }
        
        private WindowBase AsyncLoadPanel(string name)
        {
            if (!_cachedWindowDict.TryGetValue(name, out var window))
            {
                var handle = Addressables.LoadAssetAsync<Object>($"Assets/GameDesign/UI/{name}");
                _cachedWindowDict.Add(name, window);
            }

            return window;
        }

        public WindowBase OpenPanel(string name, params object[] objs)
        {
            if (CurrentWindow != null)
            {
                if (CurrentWindow.name == name && CurrentWindow.showStatusType == ShowStatusType.PERSISTENCE)
                {
                    return CurrentWindow;
                }
            }

            if (!_cachedWindowDict.TryGetValue(name, out var window))
            {
                window = AsyncLoadPanel(name);
                ShowPanel(window, objs);
            }
            else
            {
                ShowPanel(window, objs);
            }

            return window;
        }

        private void ShowPanel(WindowBase window, object[] objs)
        {
            if (_windowStack.Count > 0)
            {
                var lastPanel = _windowStack.Peek();
                if (lastPanel.showStatusType == ShowStatusType.PERSISTENCE)
                {
                    lastPanel.Close();
                }
            }

            _windowStack.Push(window);
            CurrentWindow = window;
            window.Show(objs);
        }
    }
}